package edu.stanford.hardon.Capture;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import edu.stanford.hardon.DatabaseHelper;
import edu.stanford.hardon.TravelCore;
import edu.stanford.hardon.TravelHardConstants;
import edu.stanford.hardon.Media.MediaType;
import edu.stanford.hardon.Media.RichMedia;

/**
 * Adapted from a tutorial by Ben McCann at http://benmccann.com
 */
public class AudioRecorder {

	private MediaRecorder recorder;
	private File audioFile;

	public AudioRecorder() {
	}

	/**
	 * Starts a new recording.
	 */
	public void record() throws IOException {

		recorder = new MediaRecorder();

		String state = android.os.Environment.getExternalStorageState();
		if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
			throw new IOException("SD Card is not mounted.  It is " + state + ".");
		}

		//choose the file to write
		File audio = null;
		boolean freeFile = false;
		int currentFreeFile = 0;

		while(!freeFile){
			audio=new File(Environment.getExternalStorageDirectory(), "audio" + currentFreeFile + ".mp4");

			if (audio.exists()) currentFreeFile++;
			else freeFile = true;
		}

		this.audioFile = audio;
		Log.i("AUDIO", audio.getPath());

		Log.i("Debug", "d1");


		recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);

		recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 

		recorder.setOutputFile(audioFile.getPath());

		Log.i("Debug", "d2");

		recorder.prepare();

		Log.i("Debug", "d3");

		recorder.start();

	}

	/**
	 * Stops a recording that has been previously started.
	 */
	public void stopRecording() throws IOException {
		recorder.stop();
		recorder.release();
	}

	public File getAudioFile() {
		return audioFile;
	}

	public void setAudioFile(File audioFile) {
		this.audioFile = audioFile;
	}

}